import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from "axios";
export const useStockStore = defineStore('stock', () => {
    // 状态定义 - 根据接口字段调整
    const stockList = ref([])
    const loading = ref(false)
    const error = ref('')

    // 搜索参数
    const searchParams = ref({
        vaccineName: '',
        manufacturer: '',

    })

    // 分页信息
    const pagination = ref({
        currentPage: 1,
        pageSize: 10,
        total: 0
    })

    // 计算属性
    const stockStatistics = computed(() => {


        const total = stockList.value.length
        const sufficient = stockList.value.filter(item => item.stockStatus === 'NORMAL').length
        const lowStock = stockList.value.filter(item => item.stockStatus === 'LOW').length
        const outOfStock = stockList.value.filter(item => item.stockStatus === 'OUT').length


        return { total, sufficient, lowStock, outOfStock }
    })

    // 库存状态映射（接口英文 -> 页面中文）
    const stockStatusMap = computed(() => ({
        'NORMAL': '正常',
        'LOW': '库存不足',
        'OUT': '缺货',
        'OVER': '库存过剩'
    }))

    // 过滤后的列表
    const filteredStockList = computed(() => {
        let filtered = stockList.value

        if (searchParams.value.vaccineName) {
            filtered = filtered.filter(item =>
                item.vaccineName.toLowerCase().includes(searchParams.value.vaccineName.toLowerCase())
            )
        }

        if (searchParams.value.manufacturer) {
            filtered = filtered.filter(item =>
                item.manufacturer === searchParams.value.manufacturer
            )
        }

        if (searchParams.value.stockStatus) {
            // 将中文状态映射回英文进行筛选
            const statusMap = {
                '正常': 'NORMAL',
                '库存不足': 'LOW',
                '缺货': 'OUT'
            }
            const englishStatus = statusMap[searchParams.value.stockStatus]
            filtered = filtered.filter(item => item.stockStatus === englishStatus)
        }

        if (searchParams.value.storageCondition) {
            filtered = filtered.filter(item =>
                item.storageCondition === searchParams.value.storageCondition
            )
        }

        return filtered
    })

    // Actions
    const setSearchParams = (params) => {
        searchParams.value = { ...searchParams.value, ...params }
    }

    const setPagination = (pageInfo) => {
        pagination.value = { ...pagination.value, ...pageInfo }
    }

    const setLoading = (isLoading) => {
        loading.value = isLoading
    }

    const setError = (errorMsg) => {
        error.value = errorMsg
    }

    // 获取库存数据
    const fetchStockData = async () => {
        setLoading(true)
        setError('')
        try {

            await axios.get("http://127.0.0.1:8081/vaccine/stock/list", {
                headers: {
                    'X-Admin-Token': sessionStorage.getItem("token")
                },
                params: {
                    page: pagination.value.currentPage,
                    size: pagination.value.pageSize,

                }
            }).then((req) => {

                stockList.value = req.data.Data
                console.log(stockList);

                pagination.value.total = req.data.total
            })
        } catch (err) {
            setError('获取库存数据失败，请稍后重试')
            console.error('获取库存数据失败:', err)
        } finally {
            setLoading(false)
        }
    }

    // 更新库存项
    const updateStockItem = async (id, adjustQuantity) => {
        const Data = {
            id: id,
            availableQuantity: adjustQuantity
        }
        try {
            const req = await axios.put("http://127.0.0.1:8081/vaccine/stock/Update", Data, {
                headers: {
                    'X-Admin-Token': sessionStorage.getItem("token")
                }
            }).then((req) => {

                return req.data
            })
            return req
        } catch (err) {
            setError('更新库存失败')
            throw err
        }
    }

    // 重置搜索
    const resetSearch = () => {
        searchParams.value = {
            vaccineName: '',
            manufacturer: '',
            stockStatus: '',
            storageCondition: ''
        }
    }

    return {
        // 状态
        stockList,
        loading,
        error,
        searchParams,
        pagination,

        // 计算属性
        stockStatistics,
        stockStatusMap,
        filteredStockList,

        // Actions
        setSearchParams,
        setPagination,
        setLoading,
        setError,
        fetchStockData,
        updateStockItem,
        resetSearch
    }
})